<?php
namespace app\common\model;
use think\Model;

/**
 * 需求模块
 */
class Need extends Model {
	protected $insert = ['add_time'];

    protected function setAddTimeAttr(){
        return time();
    }

    protected static function init(){
        self::beforeInsert(function($data){
            $data['order_no'] = date('YmdHis').rand(1000,9999);
        });
    }


    //需求列表
    public function needList($where=[]){

    }

    //地图需求列表
    public function needByMap($where = []){
        //未过期有偿已支付和无偿的列表
        return $this->alias('n')->join(['bz_need_position'=>'p'],'p.foreign_key = n.id','left')->where($where)->where('end_time','gt',time())->select();
        
    }

    /**
     * [getInfo 需求详情]
     * @param  array  $where [description]
     * @param  string $lng   [当前用户经度]
     * @param  string $lat   [当前用户纬度]
     * @return [type]        [description]
     */
    public function getInfo($where=[],$lng = '',$lat = ''){

        $info = $this->alias('n')->join(['bz_user'=>'u'],'u.id = n.user_id')->join(['bz_need_position'=>'p'],'p.foreign_key = n.id')->group('n.id')->where($where)->field('n.*,u.id as user_id,photo_path,nick_name,last_login_lng,last_login_lat,kaopu,service_count,tag,FROM_UNIXTIME(end_time,"%Y-%m-%d %H:%i") as end_time,p.lng as position_lng,p.lat as position_lat,p.address as position_address')->find();

        if(is_null($info)){
            return $info;
        }

        //图片
        if($info['image']){
            $info['image'] = explode(',',$info['image']);
        }else{
            $info['image'] = [];
        }

        //会员标签
        if($info['tag']){
            $info['tag'] = explode(',',$info['tag']);
        }else{
            $info['tag'] = [];
        }

        //距离该发布者距离
        $info['juli'] = round(get_distance($lat,$lng,$info['last_login_lat'],$info['last_login_lng'])/1000,4);

        $info['applyer'] = $this->applyer($info['id']);

        return $info;
    }


    /**
     * [applyer 需求申请者列表]
     * @return [type] [description]
     */
    public function applyer($id,$p=0){
        $model = db('need_apply')->alias('a')->join(['bz_user'=>'u'],'u.id = a.apply_user','left')->where('foreign_key',$id);
        if($p > 0){
            $moel->limit(($p-1)*config('page_size'),config('page_size'));
        }else{
            $model->limit(5);
        }
        $list = $model->order('a.id desc')->select();
        return  empty($list) ? [] : $list;
    }



    
}
